<template>
  <!--动态表单的验证，表格的验证 -->
  <div class="dynamic-from-box">
    <h1>动态表单的校验</h1>
    <el-form
      ref="dynamicForm"
      :model="dynamicForm"
      class="dome-dynamic"
      label-width="180px"
    >
      <el-form-item
        v-for="(item,index) in dynamicForm.dataList"
        :key="item.id"
        :label="`课程名称:${item.title}`"
        :prop="`dataList.${index}.name`"
        :rules="{
          required:true, message:`${item.title}课程名称不能为空`,
          trigger:['blur','change']  
        }"
      >
        <el-input
          v-model="item.name"
          style="width: 280px;"
        />
      </el-form-item>
      <!--提交,重置 -->
      <el-form-item>
        <el-button
          type="primary"
          @click="submitForm"
        >
          提交
        </el-button>
        <el-button @click="resetForm">
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { 
  defineComponent,reactive,onBeforeMount,getCurrentInstance
} from "vue"
export default defineComponent({
  name:"DynamicForm",
  setup() {
    let vm = ""
    const dynamicForm = reactive({
      dataList:[
        { id:0,title:"vue",name:"" },
        { id:1,title:"react",name:"" },
        { id:2,title:"angluar",name:"" },
        { id:3,title:"node",name:"" }
      ]
    })

    const submitForm = () => {
      vm.refs.dynamicForm.validate(valid => {
        if(valid) {
          console.log("dymic-form提交成功")
        }else{
          console.log("dymic-form提交失败")
          return false
        }
      })
    }

    const resetForm = () => {
      vm.refs.dynamicForm.resetFields()
    }

    onBeforeMount(() => {
      vm = getCurrentInstance() // 获取组件实例
    })

    return {
      dynamicForm,
      submitForm,
      resetForm
    }
  } 
})
</script>
<style lang='less' scoped>
  .dynamic-from-box {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
  }
</style>